package com.ebt.m.utils.android;

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;



import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;

import com.ebt.m.AppContext;
import com.ebt.m.utils.ConfigData;

/**
 * ConnectionDetector(v 1.0.0)
 * 主要功能 : <br>
 * 检查设备联网状态<br>
 * 1.是否有网络连接<br>
 * 2.判断MOBILE移动网络是否可用<br>
 * 3.判断WIFI网络是否可用<br>
 * 4.判断是否可以连接服务器<br>
 *
 * @author ZhanWu.Li
 * @create 2013.12.27
 */
public class ConnectionDetector {

    public static final String DATA_SYNC_WIFI_ONLY = "data_sync_wifi_only";
    /**
     * 网络状态获取异常
     */
    public static final int NETWORK_STATE_ERROR = -2;
    /**
     * 网络状态当前没有连接
     */
    public static final int NETWORK_STATE_NO_CONNECTION = -1;
    /**
     * 当前使用的是手机网络
     */
    public static final int NETWORK_TYPE_MOBILE = 0;
    /**
     * 当前使用的是wifi
     */
    public static final int NETWORK_TYPE_WIFI = 1;
    /**
     * 当前使用的是3g
     */
    public static final int NETWORK_TYPE_3G = 2;

    private static final String DAT_SERVER = "datv2.e-baotong.cn";

    private static final String RES_SERVER = "resv2.e-baotong.cn";

    private static final String USC_SERVER = "uacserver.e-bao.cn";

    private static final String CAM_SERVER = "cam.e-baotong.cn";

    private static final String CAS_SERVER = "cas.e-baotong.cn";

    private static final String CAS_WS_SERVER = "ws.e-baotong.cn";

    private static final String WS_SERVER = "ws.e-bao.cn";


    public static final int REACHABLE = 1;

    public static final int NOTREACHABLE = 0;

    public static final String RESULT = "result";

    private static Map<String, String> serverMap = new HashMap<String, String>();

    static {
//		serverMap.put("datv2.e-baotong.cn", "123.56.45.241:9089");
//		serverMap.put("resv2.e-baotong.cn", "123.57.2.207:9089");
//		serverMap.put("uacserver.e-bao.cn", "210.71.253.102:8086");
//		serverMap.put("cam.e-baotong.cn", "114.215.168.70:80");
//		serverMap.put("cas.e-baotong.cn", "114.215.168.70:80");
//		serverMap.put("ws.e-baotong.cn", "114.215.168.70:8085");
//		serverMap.put("ws.e-bao.cn", "114.215.168.70:80");
        //使用域名作为检测网络
        serverMap.put("datv2.e-baotong.cn", "datv2.e-baotong.cn:9089");
        serverMap.put("resv2.e-baotong.cn", "resv2.e-baotong.cn:9089");
        serverMap.put("uacserver.e-bao.cn", "uacserver.e-bao.cn:8086");
        serverMap.put("cam.e-baotong.cn", "cam.e-baotong.cn:80");
        serverMap.put("cas.e-baotong.cn", "cas.e-baotong.cn:80");
        serverMap.put("ws.e-baotong.cn", "ws.e-baotong.cn:8085");
        serverMap.put("ws.e-bao.cn", "ws.e-bao.cn:80");

    }

    /**
     * 获取网络联网状态 -2:错误 -1:无连接 1:wifi 2:mobile
     *
     * @return
     */
    public static int getNetStatus() {

        Context context = AppContext.getInstance();
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                            return NETWORK_TYPE_WIFI;
                        } else {
                            return NETWORK_TYPE_3G;
                        }
                    } else {
                        return NETWORK_STATE_NO_CONNECTION;
                    }
                } else {
                    return NETWORK_STATE_NO_CONNECTION;
                }
            }
        } catch (Exception e) {
            return NETWORK_STATE_ERROR;
        }
        return NETWORK_STATE_ERROR;
    }

    /**
     * 判断是否有网络连接
     *
     * @return
     */
    public static boolean isNetworkConnected() {
        Context context = AppContext.getInstance();
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断WIFI网络是否可用
     *
     * @return
     */
    public static boolean isWifiConnected() {
        Context context = AppContext.getInstance();
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断MOBILE网络是否可用
     */
    public static boolean isMobileConnected() {
        Context context = AppContext.getInstance();
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断是否可以连接服务器
     *
     * @return
     */
    public static boolean isConnectedToServer() {
        boolean isReach = false;
        HttpURLConnection mHttpURLConnection = null;
        Log.d("ConnectionDetector", "isConnectedToServer start");
        URL mUrl = null;
        int responseCode = 0;
        try {
            //mUrl = new URL("http://dat.e-bao.cn:9089/UpLoadWebService.asmx");
            mUrl = new URL(DownloaderConstants.URL_DOWNLOADWEBSERVICE_RES);
            //mUrl = new URL("http://www.baidu.com");
            mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mHttpURLConnection.setAllowUserInteraction(true);
            mHttpURLConnection.setRequestMethod("GET");
            //mHttpURLConnection.setReadTimeout(2000);
            mHttpURLConnection.setConnectTimeout(5000);
            mHttpURLConnection.setRequestProperty("User-Agent", "NetFox");

            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            mHttpURLConnection.connect();
            responseCode = mHttpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK
                    || responseCode == 206 || responseCode == 404) {
                isReach = true;
            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            isReach = false;
            return isReach;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            isReach = false;
            return isReach;
        } catch (IOException e) {

            e.printStackTrace();
            isReach = false;
            return isReach;
        } finally {
            mHttpURLConnection.disconnect();
        }
        if (ConfigData.DEBUG) {
            Log.d("ConnectionDetector", "isConnectedToServer end");

        }

        return isReach;

    }

    /**
     * 获取当前的网络状态
     *
     * @return -1:没有网络 1:wifi 2:wap 3: net网络
     */
    public static int getAPNType() {
        Context context = AppContext.getInstance();
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            return NETWORK_STATE_NO_CONNECTION;
        }
        switch (networkInfo.getType()) {
            case ConnectivityManager.TYPE_MOBILE:
                return NETWORK_TYPE_MOBILE;
            case ConnectivityManager.TYPE_WIFI:
                return NETWORK_TYPE_WIFI;
            default:
                return NETWORK_STATE_NO_CONNECTION;
        }
    }


    /**
     * 检查保险公司，保险产品
     *
     * @param handler
     */
    public static void checkWikiResServer(final Handler handler) {

        new Thread() {
            public void run() {
                Message msg = new Message();
                Bundle data = new Bundle();


                String IPAdress = serverMap.get(RES_SERVER);
                boolean isResReach = isReachServer(IPAdress);
                if (!isResReach) {
                    if (handler != null) {
                        data.putBoolean(RESULT, isResReach);
                        msg.what = NOTREACHABLE;
                        msg.setData(data);
                        handler.sendMessage(msg);
                    }
                    return;
                }
                IPAdress = serverMap.get(DAT_SERVER);
                boolean isDatReach = isReachServer(IPAdress);
                if (isResReach && isDatReach) {
                    if (handler != null) {
                        data.putBoolean(RESULT, true);
                        msg.what = REACHABLE;
                        msg.setData(data);
                        handler.sendMessage(msg);
                    }
                } else {
                    if (handler != null) {
                        data.putBoolean(RESULT, false);
                        msg.setData(data);
                        msg.what = NOTREACHABLE;
                        handler.sendMessage(msg);
                    }
                }
            }

            ;
        }.start();

    }

    /**
     * 检查保险公司，保险产品(建议在子线程中调用)
     */
    public static boolean checkWikiResServer() {


        String IPAdress = serverMap.get(RES_SERVER);
        boolean isResReach = isReachServer(IPAdress);

        IPAdress = serverMap.get(DAT_SERVER);
        boolean isDatReach = isReachServer(IPAdress);
        if (isResReach && isDatReach) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查调用ws(apk版本更新,发送计划书，发送短息)
     *
     * @param handler
     */
    public static void checkWSServer(final Handler handler) {

        new Thread() {
            public void run() {
                Message msg = new Message();
                Bundle data = new Bundle();

                String IPAdress = serverMap.get(WS_SERVER);
                boolean isResReach = isReachServer(IPAdress);
                data.putBoolean(RESULT, isResReach);
                msg.setData(data);
                if (!isResReach) {
                    if (handler != null) {

                        msg.what = NOTREACHABLE;

                        handler.sendMessage(msg);
                    }
                } else {
                    if (handler != null) {

                        msg.what = REACHABLE;
                        handler.sendMessage(msg);
                    }
                }

            }

            ;
        }.start();

    }

    /**
     * 检查调用ws(apk版本更新,发送计划书，发送短息)
     */
    public static boolean checkWSServer() {


        String IPAdress = serverMap.get(WS_SERVER);
        boolean isResReach = isReachServer(IPAdress);
        return isResReach;
    }

    /**
     * 检查调用 CAS ws(名片的下载，云计划书消息)
     *
     * @param handler
     */
    public static void checkCASWSServer(final Handler handler) {

        new Thread() {
            public void run() {
                Message msg = new Message();
                Bundle data = new Bundle();

                String IPAdress = serverMap.get(CAS_WS_SERVER);
                boolean isResReach = isReachServer(IPAdress);
                data.putBoolean(RESULT, isResReach);
                msg.setData(data);
                if (!isResReach) {
                    if (handler != null) {

                        msg.what = NOTREACHABLE;

                        handler.sendMessage(msg);
                    }
                } else {
                    if (handler != null) {

                        msg.what = REACHABLE;
                        handler.sendMessage(msg);
                    }
                }

            }

            ;
        }.start();

    }

    /**
     * 检查调用 CAS ws(名片的下载，云计划书消息)
     *
     */
    public static boolean checkCASWSServer() {


        String IPAdress = serverMap.get(CAS_WS_SERVER);
        boolean isResReach = isReachServer(IPAdress);
        return isResReach;
    }

    /**
     * 或作公司服务器更新
     *
     * @param handler
     */
    public static void checkCorpCompanyServer(final Handler handler) {

        new Thread() {
            public void run() {
                Message msg = new Message();
                Bundle data = new Bundle();

                String IPAdress = serverMap.get(RES_SERVER);
                boolean isResReach = isReachServer(IPAdress);
                if (!isResReach) {
                    if (handler != null) {
                        data.putBoolean(RESULT, isResReach);
                        msg.what = NOTREACHABLE;
                        msg.setData(data);
                        handler.sendMessage(msg);
                    }
                    return;
                }
                IPAdress = serverMap.get(DAT_SERVER);
                boolean isDatReach = isReachServer(IPAdress);
                data.putBoolean(RESULT, isResReach && isDatReach);
                msg.setData(data);
                if (isResReach && isDatReach) {
                    if (handler != null) {
                        msg.what = REACHABLE;
                        handler.sendMessage(msg);
                    }
                } else {
                    if (handler != null) {
                        msg.what = NOTREACHABLE;
                        handler.sendMessage(msg);
                    }
                }
            }

            ;
        }.start();

    }
/*	private static boolean isReachServer(String addressStr){
        boolean isReach=false;
		InetAddress address;
		try {
			address = InetAddress.getByName(addressStr);
			
		    isReach= address.isReachable(3000);
		
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isReach;
	}*/

    private static boolean isReachServer(String IPAdress) {
        boolean isReach = true;
        Socket client = null;
        int post = 0;
        String ip = "";
        if (IPAdress == null || IPAdress.isEmpty()) {
            return false;
        }

        try {
            String[] adress = IPAdress.split(":");

            ip = adress[0];
            post = Integer.parseInt(adress[1]);

            if (ip == null || ip.isEmpty() || post == 0) {
                return false;
            }
            client = new Socket(ip, post);
            client.setSoTimeout(1000);
            client.sendUrgentData(0xFF);
        } catch (Exception ex) {
            isReach = false;
            ex.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        return isReach;
    }


    /**
     * 是否仅使用wifi设置符合
     *
     * @return
     */
    public static boolean isNetWorkSettingOk() {
        Context context = AppContext.getInstance();

        SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(context);
        boolean wifiOnly = mSettings.getBoolean("", true);
        //getBoolean(StateManager.DATA_SYNC_WIFI_ONLY);
        int apnType = getAPNType();
        if (wifiOnly && apnType == NETWORK_TYPE_WIFI) {
            return true;
        } else if (!wifiOnly && apnType != NETWORK_STATE_NO_CONNECTION) {
            return true;
        } else {
            return false;
        }
    }


}
